import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { isEmpty } from '@/utils'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/init-config', '/404'] // no redirect whitelist
let dynamicRoutesFetched = false

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  let token = getToken()

  //外部登录功能
  /*if (to.query.token) {
    token = to.query.token
    setToken(token)
    next()
    parseQueryString('token', false, true)
  }*/

  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (isEmpty(store.getters.dynamicRoutes) && !dynamicRoutesFetched) {
        store
          .dispatch('sys/getDynamicRoutes')
          .then(dynamicRoutes => {
            if (isEmpty(dynamicRoutes)) {
              next(`/404`)
            } else {
              next({ ...to, replace: true })
            }
          })
          .catch(e => {
            next(`/404`)
          })
          .finally(e => {
            dynamicRoutesFetched = true
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      //子系统集成
      if (window.__POWERED_BY_QIANKUN__ || window.top !== window) {
        next(`/404`)
      }
      //独立启动
      else {
        next(`/login`)
      }
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export function getPageBtnHash() {
  let authButtons = store.getters?.authButtons?.[router.currentRoute.path]
  // 分解连缀的权限词, 例如: ['启用/停用'] 拆分成: ['启用','停用']
  authButtons?.forEach((item, index) => {
    const splitArr = item.split('/')
    if (splitArr.length > 1) {
      authButtons.splice(index, 1)
      splitArr.forEach(key => {
        authButtons.push(key)
      })
    }
  })
  return Object.fromEntries(Array.from(authButtons || [], v => [v, true]))
}
